<template>
  <div class="roles">
    <h2 class="page-title">角色管理</h2>
    
    <el-card class="page-card">
      <!-- 操作栏 -->
      <div class="action-bar">
        <el-button type="primary" @click="handleAdd" v-if="hasPermission('role:create')">
          <el-icon><Plus /></el-icon>
          新增角色
        </el-button>
      </div>

      <!-- 表格 -->
      <el-table :data="tableData" style="width: 100%; margin-top: 20px" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="code" label="角色代码" width="150" />
        <el-table-column prop="name" label="角色名称" width="150" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="created_at" label="创建时间" width="180" />
        <el-table-column label="操作" fixed="right" width="260">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              size="small"
              @click="handleEdit(row)"
              v-if="hasPermission('role:update')"
            >
              编辑
            </el-button>
            <el-button
              type="success"
              link
              size="small"
              @click="handleAssignResources(row)"
              v-if="hasPermission('role:assign_resource')"
            >
              分配权限
            </el-button>
            <el-button
              type="danger"
              link
              size="small"
              @click="handleDelete(row)"
              v-if="hasPermission('role:delete') && row.code !== 'super_admin'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.page_size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="fetchData"
          @current-change="fetchData"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        :model="form"
        :rules="rules"
        ref="formRef"
        label-width="100px"
      >
        <el-form-item label="角色代码" prop="code">
          <el-input v-model="form.code" :disabled="!!form.id" placeholder="如：admin" />
        </el-form-item>
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" placeholder="如：管理员" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">确定</el-button>
      </template>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog
      v-model="resourceDialogVisible"
      title="分配权限"
      width="600px"
    >
      <el-tree
        ref="treeRef"
        :data="resourceTree"
        show-checkbox
        node-key="id"
        :props="{ children: 'children', label: 'name' }"
        :default-checked-keys="checkedResources"
      />
      <template #footer>
        <el-button @click="resourceDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveResources" :loading="submitting">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { getRoles, createRole, updateRole, deleteRole, assignResources, getRoleResources } from '@/api/roles'
import { getResourceTree } from '@/api/resources'
import { ElMessage, ElMessageBox } from 'element-plus'

const userStore = useUserStore()

const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const resourceDialogVisible = ref(false)
const dialogTitle = ref('新增角色')
const formRef = ref(null)
const treeRef = ref(null)

const pagination = reactive({
  page: 1,
  page_size: 10,
  total: 0
})

const tableData = ref([])
const resourceTree = ref([])
const checkedResources = ref([])
const currentRole = ref(null)

const form = ref({
  id: null,
  code: '',
  name: '',
  description: ''
})

const rules = {
  code: [
    { required: true, message: '请输入角色代码', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' }
  ]
}

// 权限检查
const hasPermission = (permission) => {
  return userStore.hasPermission(permission)
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      page_size: pagination.page_size
    }
    const res = await getRoles(params)
    if (res.data) {
      tableData.value = res.data.items || []
      pagination.total = res.data.total || 0
    }
  } catch (error) {
    console.error('Fetch roles error:', error)
  } finally {
    loading.value = false
  }
}

// 获取资源树
const fetchResourceTree = async () => {
  try {
    const res = await getResourceTree()
    if (res.data) {
      resourceTree.value = res.data
    }
  } catch (error) {
    console.error('Fetch resource tree error:', error)
  }
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增角色'
  form.value = {
    id: null,
    code: '',
    name: '',
    description: ''
  }
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑角色'
  form.value = {
    id: row.id,
    code: row.code,
    name: row.name,
    description: row.description
  }
  dialogVisible.value = true
}

// 提交
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        if (form.value.id) {
          await updateRole(form.value.id, form.value)
          ElMessage.success('更新成功')
        } else {
          await createRole(form.value)
          ElMessage.success('创建成功')
        }
        dialogVisible.value = false
        fetchData()
      } catch (error) {
        console.error('Submit error:', error)
      } finally {
        submitting.value = false
      }
    }
  })
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除角色 "${row.name}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteRole(row.id)
      ElMessage.success('删除成功')
      fetchData()
    } catch (error) {
      console.error('Delete error:', error)
    }
  })
}

// 分配权限
const handleAssignResources = async (row) => {
  currentRole.value = row
  
  // 获取角色已有的资源
  try {
    const res = await getRoleResources(row.id)
    if (res.data) {
      checkedResources.value = res.data.map(r => r.id)
    }
  } catch (error) {
    console.error('Fetch role resources error:', error)
    checkedResources.value = []
  }
  
  resourceDialogVisible.value = true
}

// 保存权限
const handleSaveResources = async () => {
  if (!treeRef.value || !currentRole.value) return
  
  submitting.value = true
  try {
    const checkedKeys = treeRef.value.getCheckedKeys()
    const halfCheckedKeys = treeRef.value.getHalfCheckedKeys()
    const allKeys = [...checkedKeys, ...halfCheckedKeys]
    
    await assignResources(currentRole.value.id, { resource_ids: allKeys })
    ElMessage.success('权限分配成功')
    resourceDialogVisible.value = false
  } catch (error) {
    console.error('Assign resources error:', error)
  } finally {
    submitting.value = false
  }
}

// 对话框关闭
const handleDialogClose = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

onMounted(() => {
  fetchData()
  fetchResourceTree()
})
</script>

<style scoped>
.roles {
  width: 100%;
}

.page-title {
  font-size: 24px;
  font-weight: 500;
  color: #333;
  margin-bottom: 20px;
}

.page-card {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.action-bar {
  display: flex;
  justify-content: flex-end;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>

